package com.csjbot.blackgaga.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.WindowManager;

import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.feature.settings.charge_setting.ChargeManager;
import com.csjbot.blackgaga.feature.settings.charge_setting.ChargeSettingPresenter;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.model.tcp.proxy.SpeakProxy;
import com.csjbot.blackgaga.widget.BatteryView;
import com.csjbot.coshandler.client_req.ReqFactory;
import com.csjbot.coshandler.listener.OnChargetStateListener;
import com.csjbot.coshandler.listener.OnRobotStateListener;
import com.csjbot.coshandler.listener.OnSpeakListener;
import com.iflytek.cloud.SpeechError;

/**
 * Created by jingwc on 2017/12/21.
 */

public class BatteryService extends Service {

    public static final int NO_CHARGING = 0;
    public static final int CHARGING = 1;
    public static final int BATTERY_FULL = 2;

    public static int state = NO_CHARGING;

    boolean isLoop;

    WindowManager mWindowManager;

    WindowManager.LayoutParams wmBatteryParams;

    BatteryView mBateryView;

    RobotManager robotManager;

    Handler handler;


    @Override
    public void onCreate() {
        super.onCreate();
        createBatteryView();
        init();
        startQuery();

    }

    private void startQuery() {
        new Thread(() -> {
            while (isLoop) {
                if (state == NO_CHARGING) {
                    robotManager.robot.reqProxy.getBattery();
                }
                try {
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void stopQuery() {
        isLoop = false;
    }

    private void init() {
        isLoop = true;
        handler = new Handler();
        robotManager = RobotManager.getInstance();
        robotManager.addListener(new OnChargetStateListener() {
            @Override
            public void response(int state) {
                BatteryService.state = state;
                if (state == BATTERY_FULL) {
                    ServerFactory.getSpeakInstance().startSpeaking("电量已充满!", null);
                } else if (state == CHARGING) {
                    handler.post(() -> mBateryView.setBatteryImage(R.drawable.charge));
                }
            }
        });
        robotManager.addListener(new OnRobotStateListener() {
            @Override
            public void getBattery(int battery) {
                if (state == NO_CHARGING) {
                    handler.post(() -> batteryShow(battery));
                    if (ChargeManager.charging > battery && ChargeSettingPresenter.CHECKSTATE) {
                        SpeakProxy.getInstance().startSpeaking(getApplicationContext().getString(R.string.charge_to_low), new OnSpeakListener() {
                            @Override
                            public void onSpeakBegin() {
                            }

                            @Override
                            public void onCompleted(SpeechError speechError) {
                                ChargeManager.getIntanse(getApplicationContext()).gohome();
                                new Thread(() -> {
                                    try {
                                        Thread.sleep(3000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }).start();
                                String ll = "{" + "\"x\":0," + "\"y\":0," + "\"z\":0," + "\"rotation\":0" + "}";
                                ReqFactory.getChassisReqInstance().navi(ll);//回家
                            }
                        });
                    }
                }
            }
        });
    }

    private void batteryShow(int battery) {
        if (battery <= 20) {
            mBateryView.setBatteryImage(R.drawable.battery20);
        } else if (battery > 20 && battery <= 40) {
            mBateryView.setBatteryImage(R.drawable.battery40);
        } else if (battery > 40 && battery <= 60) {
            mBateryView.setBatteryImage(R.drawable.battery60);
        } else if (battery > 60 && battery <= 80) {
            mBateryView.setBatteryImage(R.drawable.battery80);
        } else if (battery > 80 && battery <= 100) {
            mBateryView.setBatteryImage(R.drawable.battery100);
        }
    }

    private void createBatteryView() {
        mBateryView = new BatteryView(getApplicationContext());
        wmBatteryParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //设置window type
        wmBatteryParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明
        wmBatteryParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmBatteryParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmBatteryParams.gravity = Gravity.RIGHT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmBatteryParams.x = 0;
        wmBatteryParams.y = 0;

        // 设置悬浮窗口长宽数据
        wmBatteryParams.width = 180;
        wmBatteryParams.height = 80;
        mWindowManager.addView(mBateryView, wmBatteryParams);
    }


    private void removeBatteryView() {
        if (mBateryView != null) {
            //移除悬浮窗口
            mWindowManager.removeView(mBateryView);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopQuery();
        removeBatteryView();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
